package userShareModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type getShareInfoRes struct {
	UserID     model.SnowflakeIdType `json:"userId"`
	UserAvatar string                `json:"userAvatar"`
	NickName   string                `json:"nickName"`
	FileID     model.SnowflakeIdType `json:"fileID"`
	FileName   string                `json:"fileName"`
	ShareTime  int64                 `json:"shareTime"`
	ExpireTime int64                 `json:"expireTime"`
}
type getShareInfoReq struct {
	ShareId string `uri:"shareId" binding:"required"`
}

func (UserShareModuleApi) GetShareInfo(c *gin.Context) {
	var req getShareInfoReq
	if err := c.ShouldBindUri(&req); err != nil {
		logrus.Errorf("GetShareInfo ShouldBindQuery err:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	type ShareFileInfo struct {
		model.ShareModel
		UserAvatar string `gorm:"column:user_avatar"`
		NickName   string `gorm:"column:nick_name"`
		FileName   string `gorm:"column:file_name"`
	}

	var result ShareFileInfo
	if err := global.DB.Table("share_models").
		Select("share_models.*, user_models.user_avatar, user_models.nick_name, file_models.file_name").
		Joins("JOIN user_models ON share_models.user_id = user_models.id").
		Joins("JOIN file_models ON share_models.file_id = file_models.id").
		Where("share_models.share_id = ? AND file_models.del_flag = ?", req.ShareId, enums.Normal). // 添加文件未删除条件
		First(&result).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.SHARE_NOT_EXIST_OR_EXPIRED, c)
			return
		}
		logrus.Errorf("GetShareInfo First err:%v", err)
		return
	}
	if enums.IsExpired(result.ExpireTime) {
		res.FailWithCode(res.SHARE_NOT_EXIST_OR_EXPIRED, c)
		return
	}
	infoRes := getShareInfoRes{
		UserID:     result.UserID,
		UserAvatar: result.UserAvatar,
		NickName:   result.NickName,
		FileID:     result.FileID,
		FileName:   result.FileName,
		ShareTime:  result.ShareTime,
		ExpireTime: result.ExpireTime,
	}
	res.OkWithData(infoRes, c)
}
